<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElButton, ElInput, ElForm, ElFormItem, ElDialog, ElSelect, ElOption, ElPagination, ElDatePicker } from 'element-plus';

// 活动数据
const activityData = ref([]);

// 搜索条件
const searchForm = reactive({
  activityName: '',
  activityType: '',
  status: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框状态
const dialogVisible = ref(false);
// 编辑模式
const editMode = ref(false);
// 当前编辑的活动ID
const currentActivityId = ref(null);
// 表单数据
const formData = reactive({
  activityName: '',
  activityType: '',
  startTime: '',
  endTime: '',
  location: '',
  description: '',
  status: ''
});

// 表单验证规则
const rules = {
  activityName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 1, max: 100, message: '活动名称长度在1到100个字符之间', trigger: 'blur' }
  ],
  activityType: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
};

// 表单引用
const activityFormRef = ref(null);

// 加载活动数据
const loadActivityData = () => {
  // 模拟API请求，使用静态数据
  activityData.value = [
    {
      id: 1,
      activityName: '春季线上营销活动',
      activityType: '线上活动',
      startTime: '2025-03-15',
      endTime: '2025-03-31',
      location: '线上',
      description: '春季优惠促销活动',
      status: '已结束',
      createTime: '2025-02-20 10:00:00',
      updateTime: '2025-04-01 14:30:00'
    },
    {
      id: 2,
      activityName: '夏季新品发布会',
      activityType: '线下活动',
      startTime: '2025-05-20',
      endTime: '2025-05-20',
      location: '上海国际会议中心',
      description: '2025夏季新品发布',
      status: '未开始',
      createTime: '2025-03-10 09:30:00',
      updateTime: '2025-04-15 11:20:00'
    },
    {
      id: 3,
      activityName: '会员专属直播活动',
      activityType: '线上活动',
      startTime: '2025-10-01',
      endTime: '2025-10-07',
      location: '线上直播平台',
      description: '国庆节会员专属优惠',
      status: '进行中',
      createTime: '2025-09-15 16:45:00',
      updateTime: '2025-10-16 10:30:00'
    }
  ];
};

// 计算总数
const total = computed(() => activityData.value.length);

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + Number(pageSize.value);
  return activityData.value.slice(start, end);
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
};

// 处理分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 打开添加对话框
const openAddDialog = () => {
  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  editMode.value = true;
  currentActivityId.value = row.id;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除活动
const deleteActivity = (row) => {
  ElMessageBox.confirm('确定要删除该活动吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = activityData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      activityData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 保存活动
const saveActivity = () => {
  activityFormRef.value.validate((valid) => {
    if (valid) {
      const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      
      if (editMode.value) {
        // 编辑模式
        const index = activityData.value.findIndex(item => item.id === currentActivityId.value);
        if (index !== -1) {
          Object.assign(activityData.value[index], formData, { updateTime: now });
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加模式
        const newActivity = {
          id: Date.now(), // 模拟生成唯一ID
          ...formData,
          createTime: now,
          updateTime: now
        };
        activityData.value.push(newActivity);
        ElMessage.success('添加成功');
      }
      dialogVisible.value = false;
      resetForm();
    }
  });
};

// 重置表单
const resetForm = () => {
  if (activityFormRef.value) {
    activityFormRef.value.resetFields();
  }
  Object.keys(formData).forEach(key => {
    formData[key] = '';
  });
  currentActivityId.value = null;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 组件挂载时加载数据
onMounted(() => {
  loadActivityData();
});
</script>

<template>
  <div class="activity-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.activityName" placeholder="请输入活动名称" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="searchForm.activityType" placeholder="请选择活动类型" style="width: 150px;">
            <el-option label="线上活动" value="线上活动"></el-option>
            <el-option label="线下活动" value="线下活动"></el-option>
            <el-option label="混合活动" value="混合活动"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 150px;">
            <el-option label="未开始" value="未开始"></el-option>
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已结束" value="已结束"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="openAddDialog">新增活动</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="currentPageData" stripe style="width: 100%">
        <el-table-column prop="activityName" label="活动名称" width="200"></el-table-column>
        <el-table-column prop="activityType" label="活动类型" width="120"></el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="120"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="120"></el-table-column>
        <el-table-column prop="location" label="活动地点" width="150"></el-table-column>
        <el-table-column prop="description" label="活动描述" width="200"></el-table-column>
        <el-table-column prop="status" label="状态" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" link @click="deleteActivity(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      ></el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editMode ? '编辑活动' : '新增活动'"
      width="600px"
    >
      <el-form
        ref="activityFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="formData.activityName" placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="formData.activityType" placeholder="请选择活动类型">
            <el-option label="线上活动" value="线上活动"></el-option>
            <el-option label="线下活动" value="线下活动"></el-option>
            <el-option label="混合活动" value="混合活动"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="活动地点">
          <el-input v-model="formData.location" placeholder="请输入活动地点"></el-input>
        </el-form-item>
        <el-form-item label="活动描述">
          <el-input v-model="formData.description" placeholder="请输入活动描述" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="未开始" value="未开始"></el-option>
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已结束" value="已结束"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveActivity">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.activity-container {
  padding: 20px;
}

.search-area {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-area {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>